import Vue from 'vue';
const RESPONSE_TYPE_SUCCESS = '10000';

export default async function(
	config, {
		useBaseURLAsPrefix = true,
		shouldLoadingShow = true,
		shouldErrorToastShow = true
	} = {
		useBaseURLAsPrefix: true,
		shouldLoadingShow: true,
		shouldErrorToastShow: true
	}
) {
	if (useBaseURLAsPrefix) {
		config.url = `${Vue.prototype.$fmBaseURL}${config.url}`;
	}
	if (shouldLoadingShow) {
		uni.showLoading({
			title: '请稍候...',
			mask: true
		});
	}
	let response;
	try {
		response = await uni.uploadFile(config);
	} catch (e) {
		throw e;
	} finally {
		if (shouldLoadingShow) {
			uni.hideLoading();
		}
	}

	const [error, {
		statusCode,
		data: dataString
	}] = response;
	if (error) {
		throw error;
	}
	
	if (statusCode === 401) {
		uni.reLaunch({
			url: '/modules/register/pages/index/index'
		});
		return {
			success: false,
			data: ''
		};
	}
	const data = JSON.parse(dataString.replace(/:null/g, ':""').replace(/:"null"/, ':""'));
	const success = data.code === RESPONSE_TYPE_SUCCESS;
	if (shouldErrorToastShow && !success) {
		uni.showToast({
			title: data.msg || '请求失败，请联系管理员',
			icon: 'none'
		});
	}

	return {
		...data,
		success
	};
}
